package com.wsd.smartcarwasher.service;

import com.wsd.smartcarwasher.annotation.Log;
import com.wsd.smartcarwasher.constans.Global;
import com.wsd.smartcarwasher.dao.UserCouponDao;
import com.wsd.smartcarwasher.domain.Coupon;
import com.wsd.smartcarwasher.domain.CouponEntity;
import com.wsd.smartcarwasher.domain.UserCoupon;
import com.wsd.smartcarwasher.util.CouponUtil;
import com.wsd.smartcarwasher.util.DateUtil;
import com.wsd.smartcarwasher.util.RandomUtils;
import com.wsd.smartcarwasher.util.StringUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserCouponService {

    @Resource
    private UserCouponDao userCouponDao;

    public int addUserCoupon(UserCoupon userCoupon) {
        userCoupon.setUserCouponId(generateUserCouponId());
        return userCouponDao.addUserCoupon(userCoupon);
    }

    public UserCoupon addUserCoupon(String userId, Coupon coupon) {
        UserCoupon userCoupon = new UserCoupon();
        userCoupon.setUserCouponId(generateUserCouponId());
        userCoupon.setUserId(userId);
        userCoupon.setCouponId(coupon.getCouponId());
        Date addTime = DateUtil.getSysTime();
        userCoupon.setAddTime(addTime);
        //添加用户使用次数的限制
        userCoupon.setUseNum(coupon.getUseNum());
        if (coupon.getValidDate() < 0) {
            userCoupon.setEndTime(null);
        } else {
            userCoupon.setEndTime(DateUtil.getDateLater(coupon.getTime(), coupon.getValidDate()));
        }
        int changeRows = addUserCoupon(userCoupon);
        if (changeRows == 0) {
            return null;
        }
        userCoupon.setCoupon(coupon);
        return userCoupon;
    }

    /**
     *  查询名下最优的优惠券
     */
    public CouponEntity getAllUnusedUserFullCoupons(String userId,BigDecimal price,String machineId) {

        List<CouponEntity> userFullCoupons = userCouponDao.getAllUnusedUserDiscountCoupons(userId, 1,machineId,price);
        //把价格最大的筛选出来
        BigDecimal initPrice=null;
        BigDecimal finalInitPrice1 = null;
        CouponEntity couponFullEntity=null;
        if(!StringUtil.isNullOrEmpty(userFullCoupons))
        {
            initPrice=userFullCoupons.get(0).getCouponPrice();
            finalInitPrice1 = initPrice;
            BigDecimal finalInitPrice2 = finalInitPrice1;
            userFullCoupons=userFullCoupons.stream().filter(s->s.getCouponPrice().compareTo(finalInitPrice2)==0).collect(Collectors.toList());
            couponFullEntity=userFullCoupons.stream().sorted(Comparator.comparing(CouponEntity::getEndTime).reversed()).collect(Collectors.toList()).get(0);
        }

        List<CouponEntity> userRateCoupons = userCouponDao.getAllUnusedUserDiscountCoupons(userId, 2,machineId,price);

        if (!StringUtil.isNullOrEmpty(userRateCoupons))
        {
            //把价格最大的筛选出来
            initPrice=userRateCoupons.get(0).getCouponRate();
            BigDecimal finalInitPrice = initPrice;
            userRateCoupons=userRateCoupons.stream().filter(s->s.getCouponRate().compareTo(finalInitPrice)==0).collect(Collectors.toList());
            CouponEntity couponRateEntity=userRateCoupons.stream().sorted(Comparator.comparing(CouponEntity::getEndTime).reversed()).collect(Collectors.toList()).get(0);
            if(couponFullEntity!=null)
            {
                System.out.println("折扣优惠券"+BigDecimal.ONE.subtract(couponRateEntity.getCouponRate()).multiply(price));
                System.out.println("普通优惠券"+couponFullEntity.getCouponPrice());
                if((BigDecimal.ONE.subtract(couponRateEntity.getCouponRate()).multiply(price)).compareTo(couponFullEntity.getCouponPrice())<0)
                {
                    return couponFullEntity;
                }else if((BigDecimal.ONE.subtract(couponRateEntity.getCouponRate()).multiply(price)).compareTo(couponFullEntity.getCouponPrice())==0)
                {
                    this.compareCouponValid(couponRateEntity,couponFullEntity);
                }
                else{
                    return couponRateEntity;
                }
            }else{
                return couponRateEntity;
            }
        }
        return couponFullEntity;
    }



    /**
     * 比较两个过期时间
     * @param cardFullEntity
     * @param cardRateEntity
     * @return
     */
    public CouponEntity compareCouponValid(CouponEntity cardRateEntity, CouponEntity cardFullEntity)
    {

        if(cardRateEntity.getEndTime().getTime()<=cardFullEntity.getEndTime().getTime())
        {
            return  cardRateEntity;
        }else{
            return  cardFullEntity;
        }
    }

    public static void main(String[] args) {
        System.out.println(DateUtil.getSysTime());
    }

    /**
     * 分享用户获取的优惠卷
     * @param userId
     * @param coupon
     * @return
     */
    public UserCoupon addUserCouponByShare(String userId, Coupon coupon,int Status) {
        UserCoupon userCoupon = new UserCoupon();
        userCoupon.setUserCouponId(generateUserCouponId());
        userCoupon.setUserId(userId);
        userCoupon.setCouponId(coupon.getCouponId());
        Date addTime = DateUtil.getSysTime();
        userCoupon.setAddTime(addTime);
        //添加用户使用次数的限制
        userCoupon.setUseNum(1);
        userCoupon.setEndTime(DateUtil.getDateLater(coupon.getTime(), coupon.getValidDate()));
        userCoupon.setStatus(Status);
        userCoupon.setCouponCode(CouponUtil.generateShortUuid());
        int changeRows = addUserCoupon(userCoupon);
        if (changeRows == 0) {
            return null;
        }
        userCoupon.setCoupon(coupon);
        return userCoupon;
    }


    public List<UserCoupon> getAllUnusedUserCoupons(String userId) {
        List<UserCoupon> userCoupons = userCouponDao.getAllUnusedUserCoupons(userId);
        if (userCoupons == null) {
            return Collections.emptyList();
        }
        return userCoupons;
    }

    public String generateUserCouponId() {
        List<String> allUserCouponIds = getAllUserCouponIds();
        String userCouponId = getUserCouponId();
        while (allUserCouponIds.contains(userCouponId)) {
            userCouponId = getUserCouponId();
        }
        return userCouponId;
    }

    private String getUserCouponId() {
        return Global.USER_COUPON_ID_PREFIX + RandomUtils.generateString(32);
    }

    private List<String> getAllUserCouponIds() {
        List<String> userCouponIds = userCouponDao.getAllUserCouponIds();
        if (userCouponIds == null) {
            return Collections.emptyList();
        }
        return userCouponIds;
    }
    @Log("使用了优惠卷")
    int useUserCoupon(Date usedTime, String userCouponId) {
        UserCoupon userCoupon = this.selectUserCoupon(userCouponId);
        //无限制次数的优惠卷
        //if(userCoupon.getUseNum()==-1)return 1;
        return userCouponDao.useUserCoupon(usedTime, userCouponId);
    }

    public int rollBackUserCoupon(String userCouponId) {
        return userCouponDao.rollBackUserCoupon(userCouponId);
    }

    public UserCoupon selectUserCoupon(String userCouponId) {
        return userCouponDao.selectUserCoupon(userCouponId);
    }

    public List<UserCoupon> getAllByCouponIdAndUserid(Integer couponId, String userId) {
        return userCouponDao.getAllByCouponIdAndUserid(couponId,userId);
    }
    //pc端查询 用户的所有优惠劵
    public List<UserCoupon> getAllUserCoupons(String userId) {

        return userCouponDao.getAllUserCoupons(userId);
    }
    //根据 优惠卷码获取优惠卷
    public UserCoupon getCouponsByCode(String couponCode) {
        return userCouponDao.getCouponsByCode(couponCode);


    }

    /**
     * 绑定优惠卷码给用户
     * @param userCoupon
     * @return
     */
    public int bindUserCouponByCode(UserCoupon userCoupon) {
        return userCouponDao.bindUserCouponByCode(userCoupon);
    }


    /**
     * 查询优惠卷 id 下未领取的 优惠卷
     * @param couponId
     * @return
     */
    public UserCoupon getValidUserCouponByCouponId(int couponId) {
        return userCouponDao.getValidUserCouponByCouponId(couponId);
    }

    /**
     * 根据用户优惠卷id
     * @param userCouponId
     * @return
     */
    public UserCoupon getUserCouponById(String userCouponId) {

        return userCouponDao.getUserCouponById(userCouponId);
    }

    /**
     * 激活用户优惠卷
     * @param userId
     * @param couponId
     */
    public void activationUserCoupon(String userId, int couponId) {
        userCouponDao.activationUserCoupon(userId,couponId);
    }

    /**
     * 检查用户有没有此类优惠卷
     * @param couponId
     * @param userId
     * @return
     */
    public UserCoupon getUserCouponByIdAndUserId(int couponId, String userId) {

        return userCouponDao.getUserCouponByIdAndUserId(couponId,userId);
    }

    public int deleteByUserCouponId(String userCouponId) {
        return userCouponDao.deleteByUserCouponId(userCouponId);
    }
}
